<template>
  <BaseDialog
    title="添加适用产品"
    append-to-body
    destroy-on-close
    :width="640"
    v-model:visible="dialogVisible"
    @confirm="handleConfirm"
    @cancel="dialogVisible = false"
  >
    <el-form
      label-position="top"
      v-if="dialogVisible"
      ref="itemFormRefCode"
      :model="productList"
      @submit.prevent
    >
      <el-form-item label="适用产品：" style="margin-bottom: 0">
        <el-form-item
          class="product-input-wrap"
          v-for="(item, index) in productList"
          :key="index"
          :prop="[index, 'code']"
          :rules="[
            {
              validator: checkoutInput,
              trigger: ['submit', 'change', 'blur']
            }
          ]"
        >
          <el-input
            placeholder="请输入适用产品编码，每行允许添加一个"
            v-model="productList[index].code"
            class="product-input"
            @input="handleChangeInput"
          ></el-input>
          <el-button style="padding: 8px" @mousedown="handleDeleteInput(index)">
            <el-icon :size="20"><Close /></el-icon>
          </el-button>
        </el-form-item>
      </el-form-item>
      <div>
        <el-button
          class="g-mt4"
          @click="handleAddInput"
          size="default"
          v-if="productList.length < 20"
          >+ 添加编码</el-button
        >
      </div>
    </el-form>
  </BaseDialog>
</template>
<script lang="ts" setup name="ApplicationCodeDialog">
import { Close } from '@element-plus/icons-vue';
import { withDefaults, defineProps, defineEmits, computed, ref, watch } from 'vue';
import { BaseDialog } from '@/components/BaseDialog/index';
import { isRepeat } from '@/utils/index';

interface AccountingBaseInfoProps {
  visible: boolean;
  code?: string;
  applyProductCode?: string[];
}
const props = withDefaults(defineProps<AccountingBaseInfoProps>(), {
  visible: false
});
const emits = defineEmits(['update:visible', 'change']);
const dialogVisible = computed<boolean>({
  get: () => {
    return props.visible;
  },
  set: val => {
    emits('update:visible', val);
  }
});

watch(
  () => dialogVisible.value,
  visible => {
    if (visible) {
      // 记录初始化的数据表
      productList.value = JSON.parse(JSON.stringify(props.applyProductCode || [])).map(
        (item: string) => {
          return {
            code: item
          };
        }
      );
    }
  }
);

function handleConfirm() {
  console.log('handleConfirm');
  itemFormRefCode.value.validate((valid: boolean) => {
    if (valid) {
      productList.value = productList.value
        .filter(item => {
          return item.code !== '';
        })
        .map(item => item.code);
      emits('change', productList.value);
      dialogVisible.value = false;
    }
  });
}

const productList = ref<any[]>([]);
const itemFormRefCode = ref();

const checkoutInput = (rule: any, value: any, callback: any) => {
  // NOTE 为空的时候不做校验
  if (!value) callback();
  if (value === props.code) {
    return callback(new Error('编码已存在'));
  } else if (isRepeat(value, productList.value) >= 2) {
    return callback(new Error('编码已存在'));
  }
  callback();
};

const handleAddInput = () => {
  productList.value.push({
    code: ''
  });
};

const handleDeleteInput = (index: number) => {
  productList.value.splice(index, 1);
  itemFormRefCode.value.validate();
};

// 每次输入时校验整个表单
function handleChangeInput() {
  itemFormRefCode.value.validate();
}
</script>
<style lang="scss" scoped>
.product-input-wrap {
  margin-bottom: 8px;
  .product-input {
    width: 400px !important;
    margin-right: 16px;
  }
  &.is-error {
    margin-bottom: 16px;
  }
}
</style>
